package main

import (
	"embed"
	"fmt"
	"io/fs"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"time"

	//"sync"

	"github.com/zserge/lorca"

	k8sclient "k8s_gui_client/k8s/client"

	functions "k8s_gui_client/functions"
)

//go:embed front-end/dist/**
var webfs embed.FS

// Go types that are bound to the UI must be thread-safe, because each binding
// is executed in its own goroutine. In this simple case we may use atomic
// operations, but for more complex cases one should use proper synchronization.
/*
type counter struct {
	sync.Mutex
	count int
}

func (c *counter) Add(n int) {
	c.Lock()
	defer c.Unlock()
	c.count = c.count + n
}

func (c *counter) Value() int {
	c.Lock()
	defer c.Unlock()
	return c.count
}*/

func main() {
	// 初始化K8s客户端
	err := k8sclient.InitK8sApiClient()
	if err != nil {
		fmt.Println("警告: K8s客户端初始化失败: " + err.Error())
		// 继续执行，允许用户稍后选择配置文件
	}

	args := []string{}
	if runtime.GOOS == "linux" {
		args = append(args, "--class=Lorca")
	}
	args = append(args, "--remote-allow-origins=*")
	ui, err := lorca.New("", "", 1000, 640, args...)
	if err != nil {
		log.Fatal("无法创建UI窗口: " + err.Error())
	}
	defer ui.Close()

	// A simple way to know when UI is ready (uses body.onload event in JS)
	ui.Bind("start", func() {
		log.Println("UI is ready")
	})

	//bind functions
	functions.Bind(ui)
	// Create and bind Go object to the UI
	/*
		c := &counter{}
		ui.Bind("counterAdd", c.Add)
		ui.Bind("counterValue", c.Value)
	*/

	// Load HTML.
	// You may also use `data:text/html,<base64>` approach to load initial HTML,
	// e.g: ui.Load("data:text/html," + url.PathEscape(html))

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		// 尝试使用固定端口作为备选方案
		ln, err = net.Listen("tcp", "127.0.0.1:8080")
		if err != nil {
			log.Fatal("无法启动HTTP服务器: " + err.Error())
		}
	}
	defer ln.Close()

	//vue build=> dist
	fdist, err := fs.Sub(webfs, "front-end/dist")
	if err != nil {
		panic(err)
	}

	// 启动HTTP服务器并添加错误处理
	go func() {
		serverErr := http.Serve(ln, http.FileServer(http.FS(fdist)))
		if serverErr != nil {
			fmt.Println("HTTP服务器错误:", serverErr)
			log.Println("HTTP服务器错误:", serverErr)
		}
	}()

	PROFILE := os.Getenv("PROFILE")

	// 记录服务器地址
	serverAddr := ln.Addr().String()
	fmt.Println("HTTP服务器已启动，监听地址:", serverAddr)

	if PROFILE == "dev" {
		fmt.Println("开发模式：加载 http://localhost:3000/")
		ui.Load("http://localhost:3000/")
	} else {
		// 构建URL并添加时间戳以禁用缓存
		loadURL := fmt.Sprintf("http://%s/index.html?t=%d", serverAddr, time.Now().UnixNano())
		fmt.Println("生产模式：加载", loadURL)

		// 设置加载超时处理
		loadSuccess := false
		go func() {
			// 5秒后检查加载状态
			time.Sleep(5 * time.Second)
			if !loadSuccess {
				fmt.Println("警告：页面加载可能超时，请检查网络连接和配置文件")
			}
		}()

		// 加载页面
		ui.Load(loadURL)
		loadSuccess = true
	}

	// You may use console.log to debug your JS code, it will be printed via
	// log.Println(). Also exceptions are printed in a similar manner.
	/*
		ui.Eval(`
			console.log("Hello, world!");
			console.log('Multiple values:', [1, false, {"x":5}]);
		`)
	*/

	// Wait until the interrupt signal arrives or browser window is closed
	sigc := make(chan os.Signal)
	signal.Notify(sigc, os.Interrupt)
	select {
	case <-sigc:
	case <-ui.Done():
	}

	log.Println("exiting...")
}
